<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import useFormEvent from '@/core/hooks/useFormEvent'
// import { isDef } from '@/core/utils/Common'
import roleApi from '@/api/system/RoleApi'
import { TreeCleanEmptyNode } from '@/core/utils/Common'
import { message } from 'ant-design-vue'

const formRef = ref() // 表单ID
const state = reactive({
  visible: false,
  loading: false, // 加载开关
  expandKeys: [], // 展开的ROWID
  // 菜单
  menuData: [],
  privilege: {}
})
// 表单结构
const original = {
  id: '',
  code: '',
  name: '',
  notes: '',
  authority: []
}
// 表单数据
const formState = reactive({})
// 表单 处理
const {
  onCancel,refreshData, InitializeData 
} = useFormEvent({ state: state, remoteApi: roleApi, formState: formState, original: original, formRef: formRef })
// 完成 保存数据
const onFinish = (values) => {
  console.info(JSON.stringify(values))
  formState.authority = []
  for(let o in state.privilege){
    if(state.privilege[o]?.hasOperate?.length > 0){
      formState.authority.push(state.privilege[o])
    }
  }
  if(formState.authority.length == 0 ){
    message.warning('请选择角色需要的操作')
    return false
  }
  state.loading = true
  roleApi.saveData(formState).then(res => {
    refreshData()
    message.success(res.msg)
    state.visible = false
  }).finally(() => {
    state.loading = false
  })
  formRef.value.clearValidate()
}

// 初始化权限菜单
const InitializeAuthority =(treeMenuData)=>{
  treeMenuData.forEach(item=> {
    state.privilege[item.moduleId] = {moduleId: item.moduleId, hasOperate: item.hasOperate}
    if(item?.children) InitializeAuthority(item.children)
  })
}

// 重写初始化 Initalize 初始化
const initializationData = primaryKey=>{
  InitializeData(primaryKey).then(()=>{
    console.info('重写初始化')
    state.menuData = formState.menus
    delete formState.menus
    TreeCleanEmptyNode(state.menuData)
    InitializeAuthority(state.menuData)
    //
    nextTick(()=>{
      state.expandKeys = []
      state.menuData.forEach(item=>{
        state.expandKeys.push(item.moduleId)
      })
    })
  })
}

//向父组件暴露方法和属性
defineExpose({ 'InitializeData': initializationData })
/*====权限列表相关=======================*/
// 定义列表字段
const columns = [
  { title: '名称', dataIndex: 'moduleName'},
  { title: '标识', dataIndex: 'moduleCode' },
  { title: '操作', dataIndex: 'actions' },
  { title: '', dataIndex: 'selectAll', width: '100px' }
]
// 全选、反选 权限
const onCheckAllNone = (privilege, options) => { 
  if(privilege.hasOperate == null) {privilege.hasOperate = []}
  if (privilege.hasOperate.length == options.length) {
    privilege.hasOperate = []
  } else {
    privilege.hasOperate = options.map(it=> it.value)
  }
}

// 页面更新
onMounted(() => {
  console.log('vue3 中的生命周期 onMounted')
})

</script>
<template>
  <a-drawer
    v-model:visible="state.visible"
    :title="`角色信息`"
    placement="right"
    :width="'70%'"
  >
    <a-card hoverable>
      <a-spin :spinning="state.loading">
        <!-- 表单内容 begin -->
        <a-form
          ref="formRef"
          :model="formState"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 10}"
          :scroll-to-first-error="true"
          :validate-on-rule-change="false"
          @finish="onFinish"
        >
          <a-row>
            <a-col :span="24">
              <a-form-item
                label="标识" name="code" :label-col="{span:3}"
                :rules="[{ required: true, message: '请输入标识!' }]"
              >
                <a-input
                  v-model:value="formState.code" show-count :minlength="5" :maxlength="20" allow-clear
                  placeholder="必须是唯一" :disabled="formState.id!=''" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="名称" name="name" :label-col="{span:3}"
                :rules="[{ required: true, message: '请输入名称!' }]">
                <a-input v-model:value="formState.name" show-count :minlength="2" :maxlength="20" allow-clear />
              </a-form-item>
            </a-col>

            <a-col :span="24">
              <a-form-item
                label="备注" name="notes" :label-col="{span:3}" :wrapper-col="{ span: 21}">
                <a-textarea v-model:value="formState.notes" show-count />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="权限" :label-col="{span:3}" :wrapper-col="{ span: 21}">
                <a-table
                  v-model:expanded-row-keys="state.expandKeys"
                  :columns="columns"
                  :data-source="state.menuData"
                  :pagination="false"
                  :row-key="record=>record.moduleId">
                  <!-- 字段 -->
                  <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex === 'actions'">
                      <a-checkbox-group v-model:value="state.privilege[record.moduleId].hasOperate" :options="record.acts" />
                    </template>
                    <template v-if="column.dataIndex === 'selectAll'">
                      <a-button type="link" @click="onCheckAllNone(state.privilege[record.moduleId], record.acts)">
                        反选
                      </a-button>
                    </template>
                  </template>
                </a-table>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item name="id">
                <a-space wrap>
                  <a-button type="primary" html-type="submit" size="large" block :loading="state.loading">保存</a-button>
                  <a-button size="large" block @click="onCancel">取消</a-button>
                </a-space>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
    </a-card>
  </a-drawer>
</template>